#!/bin/sh

die() { printf "\e[38;5;160mInit: [ERROR] %s\e[0m\n" "$1" >&2; exit 1; }

on_exit() {
	mountpoint -q /proc && umount /proc
	exec /sbin/init "$@"
}

format_overlay() {
	dmesg | grep -q "jffs2.*: Magic bitmask.*not found" || return 0
	echo -e "\e[38;5;208mInit: Invalid JFFS2 blocks detected. Formatting required.\e[0m" >&2
	umount /overlay
	flash_eraseall -j /dev/$configfs_dev
	mount_overlay || return 1
}

mount_jffs2() {
	local name mtd blk target

	name=$1
	[ -z "$name" ] && die "Missing partition name!"

	target=$2
	[ -z "$target" ] && target="/$name"

	mtd=$(awk -F: "/$name/{print \$1}" /proc/mtd)
	[ -z "$mtd" ] && die "Partition $name not found!"

	blk=$(awk -F: "/$name/{print \$1}" /proc/mtd | sed 's/mtd/mtdblock/')
	if [ ! -e "/dev/$blk" ]; then
		echo "Init: [WARNING] $name not found. Creating..."
		flash_eraseall -j /dev/$mtd
	fi

	mount -t jffs2 -o noatime /dev/$blk $target || \
		die "Failed to mount /dev/$blk as $target!"
}

trap 'on_exit "$@"' EXIT

# Mount /proc
mount -t proc proc /proc || \
	die "Failed to mount /proc!"

# Skip if rootfs is NFS, MMC or RAM
grep -q 'root=.*nfs\|mmcblk\|ram' /proc/cmdline && \
	die "Not an MTD RootFS!"

# Mount persisted overlay partition
mount_jffs2 config /overlay

grep -q overlayfs /proc/filesystems && overlay_type="overlayfs" || overlay_type="overlay"
if [ "$overlay_type" = "overlayfs" ]; then
	mount -t overlayfs overlay -o noatime,lowerdir=/,upperdir=/overlay /mnt || \
		die "Failed to mount overlay!"
else
	overlay_rootdir="/overlay/root"
	overlay_workdir="/overlay/work"
	mkdir -p "$overlay_rootdir" || die "Failed to create overlay rootdir!"
	mkdir -p "$overlay_workdir" || die "Failed to create overlay workdir!"
	mount -t overlay overlay -o noatime,lowerdir=/,upperdir="$overlay_rootdir",workdir="$overlay_workdir" /mnt || \
		die "Failed to mount overlay!"
fi

# Pivot root to overlay
pivot_root /mnt /mnt/rom || die "Failed to pivot_root!"
mount -o noatime,move /rom/proc /proc
mount -o noatime,move /rom/dev /dev
mount -o noatime,move /rom/overlay /overlay

# Mount writable rootfs_data into /opt
mount_jffs2 rootfs_data /rom/opt || die "Failed to mount rootfs_data"
mount -o noatime,move /rom/opt /opt || die "Failed to mount /opt"
